package com.mamesoft.medicipazienti.servlet;

import com.mamesoft.medicipazienti.tools.JDBC;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class RegistrationServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static Logger log = Logger.getLogger(RegistrationServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PropertyConfigurator.configure(RegistrationServlet.class.getClassLoader().getResource("com/mamesoft/medicipazienti/tools/log4j.properties"));


        Connection connect = null;
        PrintWriter out = null;
        try {
            connect = JDBC.connect();

            response.setContentType("text/html;charset=UTF-8");

            out = response.getWriter();

            log.info("Inizio invio pagina");
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("    <head>");
            out.println("        <title>Vaccino Manger</title>");
            out.println("        <link rel=\"stylesheet\" type=\"text/css\" href=\"variant-stream.css\" title=\"Variant Stream\" media=\"screen,projection\" />");
            out.println("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">       ");
            out.println("    </head>");
            out.println("    <body>");
            out.println("        <div id =\"wrap\">");
            out.println("            <div id=\"header\">");
            out.println("                <div id =\"topmenu\">");
            out.println("                    <p>");
            out.println("                        <a href=\"registrati.html\">Registrati</a>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div id=\"title\">");
            out.println("                    <h1>Vaccino Manager</h1><br/>");
            out.println("                    <h2 class =\"slogan\">I tuoi vaccini contano</h2>");
            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"sidebar\">");
            out.println("                <form action=\"/MediciPazienti/login_servlet\" method=\"POST\">");
            out.println("                    <p class =\"sidemenu\">");
            out.println("                        Username: <br/>");
            out.println("                        <input type=\"text\" name=\"user\" value=\"\" />");
            out.println("                    </p>");
            out.println("                    <p class =\"sidemenu\">");
            out.println("                        Password: <br/>");
            out.println("                        <input type=\"password\" name=\"password\" value=\"\" />");
            out.println("                    </p>");
            out.println("                    <p class =\"sidemenu\">");
            out.println("                        <select name=\"role\">");
            out.println("                            <option>-->Scegli un ruolo</option>");
            out.println("                            <option>Medico</option>");
            out.println("                            <option>Paziente</option>");
            out.println("                        </select>");
            out.println("                    </p>");
            out.println("                    <p>");
            out.println("                        <input type=\"reset\" value=\"Cancella\" />");
            out.println("                        <input type=\"submit\" value=\"Login\" />");
            out.println("                    </p>");
            out.println("                </form>");
            out.println("            </div>");
            out.println("            <div id =\"content\">");
            out.println("                <div class=\"post\">");


            ResultSet set = null;
            boolean isCaptchaOk = SimpleImageCaptchaServlet.validateResponse(request, request.getParameter("captcha"));

            if (isCaptchaOk) {
                if ((request.getParameter("role").equals("Medico")) || (request.getParameter("role").equals("Paziente"))) {
                    synchronized (connect) {
                        String s;
                        if (request.getParameter("role").equals("Medico")) {
                            s = "";
                        } else {
                            s = ",Data";
                        }
                        String query = "SELECT Nome,Cognome,Password" + s + " FROM " + request.getParameter("role").toLowerCase()
                                + " WHERE Nome = \"" + request.getParameter("nome") + "\" AND Cognome = \"" + request.getParameter("cognome") + "\"";
                        set = JDBC.executeQuery(query, connect);
                    }
                    if (set.next()) {
                        String pass = set.getString("Password");

                        boolean isAllOk = request.getParameter("role").equals("Medico");
                        if (!isAllOk) {
                            Timestamp t = set.getTimestamp("Data");
                            isAllOk = t.toString().substring(0, 4).equals(request.getParameter("anno"));
                            isAllOk = t.toString().substring(5, 7).equals(request.getParameter("mese")) && isAllOk;
                            isAllOk = t.toString().substring(8, 10).equals(request.getParameter("giorno")) && isAllOk;
                        }
                        set.close();

                        if ((pass == null) && isAllOk) {
                            String statement = "UPDATE " + request.getParameter("role").toLowerCase()
                                    + " SET Password =\"" + request.getParameter("password") + "\""
                                    + " WHERE Nome = \"" + request.getParameter("nome") + "\" AND Cognome = \"" + request.getParameter("cognome") + "\";";
                            JDBC.executeStatement(statement, connect);
                            out.println("<p>La registrazione è avvenuta con successo!</p>");
                            out.println("<p>Il tuo username è: " + request.getParameter("nome").toLowerCase()
                                    + "." + request.getParameter("cognome").toLowerCase() + "</p>");
                        } else {
                            if (isAllOk) {
                                out.println("<p>Sei gia registrato!</p>");
                                out.println("<p>Effettua il login nel form a lato.</p>");
                            } else {
                                out.println("<p>Dati non trovati, prova a ricontrollare e riprova!</p>");
                            }
                        }
                    } else {
                        out.println("<p>Dati non trovati, prova a ricontrollare e riprova!</p>");
                    }
                } else {
                    out.println("<p>Devi scegliere un ruolo!</p>");
                    out.println("<p>Torna <a href=\"registrati.html\">indietro</a></p>");
                }
            } else {
                out.println("<p>Il Captcha &egrave; errato</p>");
                out.println("<p>Torna <a href=\"registrati.html\">indietro</a></p>");
            }
            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"footer\">");
            out.println("                <p class=\"centered\">Copyright &copy; 2011 <a href=\"/MediciPazienti/index.html\">Mamesoft</a>");
            out.println("                    Progetto Programmazione per il web A.A.2011/2012</p>");
            out.println("            </div>");
            out.println("        </div>");
            out.println("    </body>");
            out.println("</html>");
            log.info("Fine invio pagina");
            
            
        } catch (Exception ex) {
            request.getSession().invalidate();
            if (ex instanceof SQLException | (ex instanceof ClassNotFoundException & ex instanceof InstantiationException & ex instanceof IllegalAccessException)) {
                log.error("Database Error: " + ex.toString());
                response.sendRedirect("/MediciPazienti/database_error.html");
            } else {
                log.error("Generic error: " + ex.toString());
                response.sendRedirect("/MediciPazienti/general_error.html");
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (connect != null) {
                try {
                    connect.close();
                } catch (Exception ex) {
                    request.getSession().invalidate();
                    log.error("Database Error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/database_error.html");
                }
            }
        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
